package com.teufandsub.socialproximity.gui;

import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;

import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.teufandsub.socialproximity.R;
import com.teufandsub.socialproximity.controller.Constants;
import com.teufandsub.socialproximity.controller.Controller;
import com.teufandsub.socialproximity.controller.Utils;
import com.teufandsub.socialproximity.logic.User;

/**
 * @author Bastien Mathias <bastienmathias@gmail.com>
 * @author Antoine Teuf <antoine.teuf@gmail.com>
 * @version 1.0
 * @since 2013-05-22
 * 
 * Adapter to fill up the friendlist, the blacklist and the waiting list.
 */

public class MyListAdapter extends ArrayAdapter<User> {
	
	public static final int FRIENDLIST=0;
	public static final int BLACKLIST=1;
	public static final int WAITINGLIST=2;
	
	private Context context;
	private Controller controller;
	private ArrayList<User> list;
	private int listType;
	private String currentUsername;
	private FriendListActivity listActivity;
	
	/**
	 * Constructor of the Adapter.
	 * 
	 * @param context Context of the application
	 * @param ArrayList<User> users list of users you want to set the view.
	 * @param listType int list type to know which view will be used.
	 */
	public MyListAdapter(Context context, ArrayList<User> users,int listType) {
		super(context,0,users);
		this.context=context;
		this.list=users;
		this.listType=listType;
		controller=Controller.getInstance();
		listActivity = FriendListActivity.getInstance();
		
		SimpleEntry<String,JSONObject> prefs = controller.getSessionInfo(context);
		currentUsername="";
		try {
			currentUsername = prefs.getValue().getString(User.USERNAME_NAME);
		} catch (Exception e) {
		}
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
	
        LayoutInflater inflater = LayoutInflater.from(context);
        final User user = list.get(position);
        
        switch(listType){
        
        	case FRIENDLIST :
        		convertView = inflater.inflate(R.layout.friend_list_layout, parent, false);
        		
        		ImageView availableIv = (ImageView) convertView.findViewById(R.id.available_iv);
        		if(user.isAvailable()){
        			availableIv.setImageResource(R.drawable.ic_connected);
        		}else{
        			availableIv.setImageResource(R.drawable.ic_disconnected);
        		}
        		
        		ImageButton profilButton = (ImageButton) convertView.findViewById(R.id.profil_button);
            	profilButton.setOnClickListener(new OnClickListener() {
        			
        			@Override
        			public void onClick(View v) {
        				Intent i = new Intent(context, UserDetailsActivity.class);
        				i.putExtra(User.KIND, user);
        				context.startActivity(i);
        			}
        		});
            	
            	ImageButton chatButton = (ImageButton) convertView.findViewById(R.id.chat_button);
            	chatButton.setOnClickListener(new OnClickListener() {
        			
        			@Override
        			public void onClick(View v) {
        				Intent i = new Intent(context, ChattingActivity.class);
        				i.putExtra(User.KIND, user);
        				if(controller.isNewConversation(user)){
        					controller.newConversation(user);
        				}
        				
        				context.startActivity(i);
        			}
        		});
            	
            	ImageButton delButton = (ImageButton) convertView.findViewById(R.id.del_button);
            	delButton.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						int code = setAction(Constants.REMOVEFRIENDLINK,
								context.getResources().getString(R.string.successful_remove_fl),
								user.getUsername(),currentUsername);
						
						if(code==Constants.CODE_REQUESTVALID){
							listActivity.removeFriend(user);
						}
					}
				});

        		break;
        	case BLACKLIST: 
        		convertView = inflater.inflate(R.layout.black_list_layout, parent, false);
        		ImageButton removeButton = (ImageButton) convertView.findViewById(R.id.remove_button);
        		removeButton.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						int code = setAction(Constants.REMOVEBLACKLINK,
								context.getResources().getString(R.string.successful_remove_bl),
								user.getUsername(),currentUsername);
						
						if(code==Constants.CODE_REQUESTVALID){
							listActivity.removeFromBlackList(user);
						}
						
					}
				});
        		break;
        		
        	case WAITINGLIST: 
        		convertView = inflater.inflate(R.layout.waiting_list_layout, parent, false);
        		ImageButton addButton = (ImageButton) convertView.findViewById(R.id.add_button);
        		addButton.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						int code = setAction(Constants.APPROVEFRIENDLINK,
								context.getResources().getString(R.string.successful_approve),
								user.getUsername(), currentUsername);
						
						if(code==Constants.CODE_REQUESTVALID){
							listActivity.addFriend(user);
						}
					}
						
				});
        		
        		ImageButton dButton = (ImageButton) convertView.findViewById(R.id.del_button);
        		dButton.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						int code = setAction(Constants.REMOVEFRIENDLINK,
								context.getResources().getString(R.string.successful_remove_wl),
								user.getUsername(), currentUsername);
						
						if(code==Constants.CODE_REQUESTVALID){
							listActivity.refusedFriendship(user);
						}
					}
				});
        		break;
        }
              
        TextView username = (TextView) convertView.findViewById(R.id.username_list);
        
        /*Set user name view */
    	if(user.showRealName()){
    		username.setText(user.getFirstname()+" "+user.getSurname());        		
    	}else{
    		username.setText(user.getUsername());
    	}
    	switch(user.getSex()){
			case User.SEX_MALE: username.setTextColor(Color.BLUE);break;
			case User.SEX_FEMALE: username.setTextColor(Color.MAGENTA);break;
		}      
		return convertView;
	}
	
	/**
	 * Method used to set the action to do on Button click.
	 * 
	 * @param action int Action to do on click on the button.
	 * @param toastAction String message to display after a successful action.
	 * @param targetNameLink String name of the targeted username link to do the action.
	 * @param usernameLink String name of the username link to do the action.
	 * @return int result of the action.
	 */
	private int setAction(final int action,final String toastAction,
			final String targetNameLink,final String usernameLink){
		
		int returnValue=Constants.CODE_ERROR;
		AsyncTask<Void, Void, JSONObject> task = new AsyncTask<Void, Void, JSONObject>() {
			
			@Override
			protected JSONObject doInBackground(Void... params) {
				JSONObject info = new JSONObject();
				try {
					info.put(Constants.ACTIONCODE_NAME, action);
					info.put(Constants.USERNAMELINK_NAME, usernameLink);
					info.put(Constants.TARGETNAMELINK_NAME, targetNameLink);
				} catch (Exception e) {
					Log.e(Constants.APP_NAME, "Error to create JSONObject to approve link");
				}
				
				return controller.manageFriend(context, info);
			}
			
			@Override
			protected void onPostExecute(JSONObject result) {
				super.onPostExecute(result);
				int code = Constants.CODE_ERROR;
				try {
					code = result.getInt(Constants.CODE_NAME);
				} catch (Exception e) {
					Log.e(Constants.APP_NAME, "Error to manage friend : " + e.toString());
				}
				
				switch(code){
					case Constants.CODE_REQUESTVALID:
						Toast.makeText(context, toastAction
								, Toast.LENGTH_LONG).show();
						break;
						
					case Constants.CODE_ERROR:
						Toast.makeText(context, context.getResources().getString(R.string.error)
								, Toast.LENGTH_LONG).show();
						break;

				}
				
			}
			
		};
		
		if(Utils.hasConnectivity(context)){
			task.execute();
			try {
				returnValue = task.get().getInt(Constants.CODE_NAME);
			} catch (Exception e) {
				Log.e(Constants.APP_NAME, "Error to get int code thanks to get" + e.toString());
			}
			
		}else{
			Toast.makeText(context, context.getResources().getString(R.string.no_connectivity), Toast.LENGTH_LONG).show();
		}
		
		return returnValue;
	}
}
